package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;

import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper  shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private WebSocketServer webSocketServer;
    //用户下单
    @Override
    @Transactional//开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //查询地址表获取收货人信息
        AddressBook detail = addressBookMapper.getById(dto.getAddressBookId());
        if(detail==null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询用户表获取用户相关信息
       User user= userMapper.selectById(BaseContext.getCurrentId());
        if(user==null){
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }
        //查询购物车列表数据
        List<ShoppingCart> cartList = shoppingCartMapper.list(BaseContext.getCurrentId());
        if(cartList==null){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //1.构造订单数据存入orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);
        orders.setNumber(System.currentTimeMillis() + "");//订单编号
        orders.setStatus(Orders.PENDING_PAYMENT);//1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);//支付状态 0未支付 1已支付 2退款Orders.UN_PAID
        orders.setPhone(detail.getPhone());
        orders.setAddress(detail.getDetail());
        orders.setConsignee(detail.getConsignee());//收获人
        orders.setUserName(user.getName());//下单人

        ordersMapper.insert(orders);
       log.info("订单id：{}",orders.getId());
        //2.构造订单明细数据存入order_detail
        List<OrderDetail> orderDetails = new ArrayList<>();
        //循环遍历购物车列表数据，构造订单明细
        cartList.forEach(cart->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail,"id");
            //关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
       //批量插入订单明细数据
        orderDetailMapper.insertBatch(orderDetails);
        //3.删除购物车
        shoppingCartMapper.clean(BaseContext.getCurrentId());
        //构造返回数据
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
     /*   // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/

        /// /////////////////////////////////////////////////////////////////
        //模拟支付成功----修改订单状态
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
        //通过websocket向客户端推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", 1);//1表示来单提醒2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
    //查看历史订单
    @Override
    public PageResult getHistoryOrders(OrdersPageQueryDTO dto) {
        //设置分页参数
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<OrdersDTO> orders= ordersMapper.select(BaseContext.getCurrentId());//临时解决id问题
        Page<OrdersDTO> page =ordersMapper.getHistoryOrders(BaseContext.getCurrentId(),dto.getStatus());
        page.getResult().forEach(ordersDTO -> {
          List<OrderDetail> list=ordersMapper.getOrderDetails(orders.get(0).getId());
            ordersDTO.setOrderDetails(list);
        });
        return new PageResult(page.getTotal(),page.getResult());
    }
    //查询订单详情
    @Override
    public OrderVO getOrderDetails(Long id) {
        //根据id查询订单
       Orders orders= ordersMapper.getOrders(id);
       //查询该套餐对应的套餐明细
       List<OrderDetail> orderDetails= ordersMapper.getOrderDetails(orders.getId());
        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;

    }
    //取消订单
    @Override
    public void cancleOrder(Long id) throws Exception {
        /*
- 待支付和待接单状态下，用户可直接取消订单
- 商家已接单状态下，用户取消订单需电话沟通商家
- 派送中状态下，用户取消订单需电话沟通商家
- 如果在待接单状态下取消订单，需要给用户退款
- 取消订单后需要将订单状态修改为“已取消”
*/
        // 查询档当前订单状态
        Orders orders=  ordersMapper.getOrders(id);
        if(orders.getStatus()>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
           /* weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/

            //支付状态修改为 退款(模拟退款成功)
            orders.setPayStatus(Orders.REFUND);
        }
        if (orders.getStatus().equals(Orders.UN_PAID)) {

        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }
    //再来一单
    @Override
    public void repetition(Long id) {
        //根据id查orders表
        Orders orders = ordersMapper.getOrders(id);
        List<OrderDetail> orderDetails = ordersMapper.getOrderDetails(orders.getId());
        orderDetails.forEach(orderDetail -> {
            //将原来的商品重新加入购物车
            ShoppingCartDTO dto = new ShoppingCartDTO();
            dto.setDishId(orderDetail.getDishId());
            dto.setSetmealId(orderDetail.getSetmealId());
            dto.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCartService.addCart(dto);
        });
    }
    //订单搜索
    @Override
    public PageResult search(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> page= ordersMapper.search(dto);
      /*  page.getResult().forEach(orderVO -> {
            List<OrderDetail> orderDetails = ordersMapper.getOrderDetails(orderVO.getId());
            orderDetails.forEach(orderDetail -> {

                orderVO.setOrderDishes(orderDetail.getName());
            });

        });*/
        // 5. 填充每个订单的菜品信息
        page.getResult().forEach(orderVO -> {
            List<OrderDetail> orderDetails = ordersMapper.getOrderDetails(orderVO.getId());
            if (orderDetails != null) {
                // 设置详情列表
                orderVO.setOrderDetailList(orderDetails);

                // 拼接菜品信息字符串
                String dishesStr = orderDetails.stream()
                        .map(d -> d.getName() + "*" + d.getNumber()) // 菜品名*数量
                        .collect(Collectors.joining(", "));
                orderVO.setOrderDishes(dishesStr);
            }
        });
        return new  PageResult(page.getTotal(),page.getResult());
    }
    //各个状态的订单数量统计
    @Override
    public OrderStatisticsVO statistics() {
        //待派送数量
       Integer sum1= ordersMapper.statisticsCONFIRMED(Orders.CONFIRMED);
        //派送中数量
        Integer sum2= ordersMapper.statisticsDELIVERY_IN_PROGRESS(Orders.DELIVERY_IN_PROGRESS );
        //待接单数量
        Integer sum3= ordersMapper.statisticsTO_BE_CONFIRMED(Orders.TO_BE_CONFIRMED);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(sum1);
        orderStatisticsVO.setToBeConfirmed(sum3);
        orderStatisticsVO.setDeliveryInProgress(sum2);
        return orderStatisticsVO;
    }
    //接单
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        dto.setStatus(Orders.CONFIRMED);
        ordersMapper.confirm(dto);
    }
    //拒单
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        ordersMapper.rejection(dto,Orders.CANCELLED);
    }
    //取消订单
    @Override
    public void cancle(OrdersCancelDTO dto) {
        Integer status = new Integer(Orders.CANCELLED);
        LocalDateTime cancelTime = LocalDateTime.now();
        ordersMapper.cancle(dto,status,cancelTime);
    }
    //派送订单
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));//预计送达时间
        //orders.setDeliveryStatus();//配送状态  1立即送出  0选择具体时间
        ordersMapper.delivery(orders);
    }
    //完成订单
    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        ordersMapper.complete(orders);
    }
    //用户催单
    @Override
    public void reminder(Long id) {
        Orders orders = ordersMapper.getOrders(id);
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号:"+orders.getNumber());
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
